package cn.edu.zut.score.service.biz;

import cn.edu.zut.score.core.constant.RoleEnum;
import cn.edu.zut.score.core.convert.UserConvert;
import cn.edu.zut.score.core.domain.ImportUser;
import cn.edu.zut.score.core.entity.Clazz;
import cn.edu.zut.score.core.entity.Info;
import cn.edu.zut.score.core.entity.User;
import cn.edu.zut.score.core.util.MDUtil;
import cn.edu.zut.score.service.IClazzService;
import cn.edu.zut.score.service.IUserService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author zby
 * @date 2021/07/29
 */
@Slf4j
@ApiModel("导入用户excel服务")
public class UserExcelService extends AnalysisEventListener<ImportUser> {

    private final List<Info> allClass;

    private final IUserService iUserService;

    private final IClazzService iClazzService;

    private final RoleEnum roleEnum;

    public UserExcelService(IUserService iUserService, IClazzService iClazzService, RoleEnum roleEnum) {
        this.allClass = iClazzService.queryAllClasses().getResult();
        this.iUserService = iUserService;
        this.iClazzService = iClazzService;
        this.roleEnum = roleEnum;
    }

    @Override
    public void invoke(ImportUser importUser, AnalysisContext analysisContext) {
        if ("男".equals(importUser.getGender())) {
            importUser.setGender("1");
        } else {
            importUser.setGender("0");
        }
        if (roleEnum == RoleEnum.student) {
            Info info = allClass.stream().filter(clazz -> clazz.getName().equals(importUser.getClazzId())).findFirst().orElse(null);
            if (info == null) {
                Clazz clazz = new Clazz();
                clazz.setName(importUser.getClazzId());
                clazz.setCount(0);
                iClazzService.saveClazz(clazz);
                info = new Info();
                info.setId(clazz.getId());
                log.info("班级:{}不存在，已创建", importUser.getClazzId());
            }
            importUser.setClazzId(String.valueOf(info.getId()));
        }
        importUser.setRole(roleEnum.getCode());
        importUser.setPassword(MDUtil.encryption("123456"));
        User user = UserConvert.INSTANCE.importUser2User(importUser);
        iUserService.saveUser(user);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("head:" + headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("finish");
    }
}
